<?php
//error_reporting(E_ALL);
class sms_controller_index extends SnsController{
	/**
	 *
	 * @var sms_model_data
	 */
	var $sms;
	/**
	 * 
	 *
	 * @var sms_model_message
	 */
	var $sms_message;
	/**
	 * 
	 *
	 * @var sms_model_reciever
	 */
	var $sms_reciever;
	
	const ERROR_NO_RECIEVER = 'err_no_reciever';
	
	const TYPE_SYSTEM = 0;
	const TYPE_USER	=	1;
	
	public function __construct($app, $controller){
		parent::__construct($app, $controller);
		$this->sms = new sms_model_data();
		$this->comment = new sms_model_comment();
		$this->headerView = $this->viewDir."/_header.phtml";
		$this->__title = '消息中心';
	}
	
	public function index_action(){
		$this->requireLogin();
		$this->uid = self::$login['uid'];
//		$this->cite = cite_util_interface::getMsgTop();
		$this->view = 'index';
	}
	
	public function test_action(){
		/*$rst = $this->sms->updateSmsCount(4892787,sms_config::MSG_CARTOON_CNT,1);
		var_dump($rst);*/
//		$rst = sms_util_system::send('fza',5164303,'testtest','system',array(0),time(),'new.178.com');
		$rst = sms_util_system::send(null, 5164303, 'testtesttest', "[:nga:]", null, $_SERVER['REQUEST_TIME']);
		var_dump($rst);exit;
	}
	
	public function clean_pms_action(){
		$this->_renderJson();
		$uid = _('uid',0);
		if($uid){
			if($ret = $this->sms->queryUnReadSms($uid,true)){
				$this->ret = self::success($ret);
			}
		}
		else $this->ret = self::success('failed!!!!');
	}

	public function test_com_action(){
		$this->requireLogin();
		$uid = self::$login['uid'];
		$ret = sms_util_system::send('bigbear1113',4892787,'hahahah','[:nga:]',array(1),time(),'','test');
		/*$params = array(
				'senderid'		=> 5164303,
				'reciverid'	=> 4892787,
				'type'	=> '[:friends|bind:]'
			);
		$senderid = 5164303;
		$reciverid = 4892787;
		$type = '[:friends|add:]';
		$ret =sms_util_system::upSmsStatus($senderid,$reciverid,$type);*/
		
//		sms_util_system::sendCiteNotice($uid);
//		sms_plugin_whatsnew::sendCiteNotice($this);
		
		//$args = array('thread_id'=>'','uid'=>'','app'=>'','control'=>'','act'=>'','rid'=>'','authorid'=>''
//		$ret = $this->sms->updateSmsCount($uid,sms_config::MSG_DKP_CNT,1);
		var_dump($ret);exit;
		/*$para = array('thread_id'=>663,'uid'=>5164303,'app'=>'blog','control'=>'index','act'=>'view_thread','rid'=>183,'authorid'=>4892787);
		$rst = sms_util_comment::upCommentLog($para,1);*/
//		var_dump($rst);
	}

	public function view_inbox_action(){
		$this->requireLogin();
//		if($this->reload) $this->additionView= $this->viewDir."/_addtion.phtml";
		$uid = self::$login['uid'];
		$page = _('page', 1);
//		$history = _('history',false);
		$ret = CacheManager::getInstance()->get(array(
			'app'=>$this->app,
			'func'=>array(
				array($this->sms, 'getInBoxpage'), 
				array($uid, $page, sms_model_message::PAGE_SIZE)				
			)
		));
		$pages = $this->genPages($ret['INFO']);
		$this->ret = self::success(array('ret'=>$ret, 'pages'=>$pages));
		$this->view = 'inbox';
	}
	
	public function view_outbox_action(){
		$this->requireLogin();
//		if($this->reload) $this->additionView= $this->viewDir."/_addtion.phtml";
		$uid = self::$login['uid'];
		$username = self::$login['nickname'];
		$page = _('page',1);
		$ret = CacheManager::getInstance()->get(array(
			'app'=>$this->app,
			'func'=>array(
				array($this->sms, 'getOutBoxpage'), 
				array($uid, $page, sms_model_message::PAGE_SIZE)				
			)
		));
		$pages = $this->genPages($ret['INFO']);
		$this->ret = self::success(array('ret'=>$ret, 'pages'=>$pages));
//		var_dump($this->ret);exit;
		$this->view = 'outbox';
	}
	
	public function system_action(){
		
	}
	
	public function mytest_action(){
		$uid = self::$login['uid'];
		$this->sms->setReaded($uid,true);
	}
	
	public function view_send_form_action(){
		$this->requireLogin();
		$this->view = 'send_form';
		if($this->reciever_id){
			$this->reciever = member_util_login::getMemberInfo($this->reciever_id,'username'); //Cache::cacheFunction(array(SecureLogin::getInstance(), 'soap_query_info'), array($this->reciever_id, '', 'nickname'));
		}
		if($this->forward){
			$id = $this->id;
			$sms_id = $this->sms_id;
			$uid = self::$login['uid'];
			$msg = $this->sms->getSmsInfoById($id);
			$cnt = count($msg);
			if($cnt<=0){
				$this->ret = self::failure(Error::ERROR_ILLEGAL);
				return;
			}
			$exists = false;
			$content = '';
			$recievers = CacheManager::getInstance()->get(array(
			'app'=>$this->app,
			'func'=>array(
			array($this->sms, 'getReciverByUid'),
			array($sms_id)
			)
			));
			$users = '';
			foreach ($recievers as $r){
				if ($r['uid']==$uid) {
					$exists = true;
					$lastdel_id = $r['sms_lastdel_msid'];
				}
				else $users.='<p>[b]'.$r['username'].':[/b]<p/>';
			}
			$i = 0;
			foreach ($msg as $v){
				$i++;
				if($v['sms_id']<=$lastdel_id || ($v['sms_senderid']==$uid && $v['sms_isdelete']==1)) continue;
				else{
					$content.='[b]'.$v['sms_sender'].':[/b]
					'.$v['sms_content'];
					if($i<$cnt){
						$content.='
						------------------------------------
						';
					}
				}
			}
//			$content = $cnt==1?$users.$content:$content;
			//echo $content;
			/*if($msg['sms_id']!=$sms_id){
				$this->ret = self::failure(Error::ERROR_ILLEGAL);
				return;
			}	
			$exists = false;
			if($msg['sms_senderid'] == $uid or $msg['sms_reciverid']==$uid){
				$exists = true;
			}else{
				$recievers = CacheManager::getInstance()->get(array(
					'app'=>$this->app,
					'func'=>array(
						array($this->sms, 'getReciverByUid'), 
						array($sms_id)				
					)
				));
				foreach($recievers as $reciever){
					if($reciever['uid'] == $uid) {
						$exists = true;
						break;
					}
				}
			}*/
//			if(!$exists){
//				$this->ret = self::failure(Error::ERROR_WRONG_OWNER );
//				return;
//			}
//			$msg['content'] = preg_replace('`\r\n|\n`', '<p>\r\n', addslashes($msg['content']));
			$this->msg = array('sms_content'=>$content);
		}
		
//		$this->_renderSingle();
	}
	
	public function reply_form_action(){
//		$this->requireLogin();
		$this->_renderSingle();
	}
	
	public function send_system_action(){
		
	}
	
	public function test_sms_action(){
		$uid = self::$login['uid'];
//		//'sms_title', 'sms_content', 'sms_sender', 'sms_senderid'
//		$args = array('sms_title'=>'测试发短消息','sms_content'=>'测试发短消息测试一下','sms_sender'=>'fza','sms_senderid'=>$uid,'sms_reciver'=>'bigbear1113','sms_reciverid'=>4892787);
//		$args = array('sms_id'=>1,'sms_uid'=>5164303,'sms_nickname'=>'fza','sms_type'=>1,'sms_last_msid'=>1,'sms_lastsend_msid'=>0);
//		$rst = $this->sms_message->getInBoxpage(4892787,1,20);
		$rst = $this->sms->delReciverSms($uid);
//		var_dump($rst);
	}
	public function send_action(){
		$this->_renderJson();
		if(!self::$login){
			$this->ret = array('result'=>false, 'reason'=>Error::ERROR_NOT_LOGIN );
		}else{
			$uid = self::$login['uid'];
			if(trim($this->reciever)==''){
				$this->ret = array('result'=>false, 'reason'=>self::ERROR_NO_RECIEVER );
			}else{
				if(Plugin::vcode_get($uid)){
					if(vcode_get2(Cache::getInstance(), 'vcode')!=strtoupper(_('vcode'))){
						$this->ret = self::failure(Error::ERROR_VCODE );
						return;
					}else{
						Plugin::vcode_clean();
					}
				}
				$recievers = explode(',', $this->reciever);
				array_push($recievers, self::$login['nickname']);
				$recievers = array_slice(array_unique($recievers),0,10);
				if(count($recievers)<2){
					$this->ret = self::failure(Error::ERROR_WRONG_PARAMS, '你必须指定一名收件人，并且不能是自己。');
					return;
				}
				$title = _('title');
				if(!$content = sms_util_text::filter_html(_('content'))){
					$this->ret = self::failure(Error::ERROR_WRONG_PARAMS);
					return false;
				}
				
				/*$sms_id = $this->sms->add(
					array(
						'uid'=>self::$login['uid'], 
						'username'=>self::$login['nickname'], 
						'reciever_count'=>count($recievers), 
						'type'=>1, 
						'message_count'=>1)
				);*/
//				$firstReciver = Cache::cacheFunction(array($this->SL, 'soap_query_user_by_username'), array($recievers[0]));
				$firstReciver = member_util_login::getMemberInfoByName($recievers[0],array('uid','username'));
				$sms_id = $this->sms->add(
					array('sms_title'=>$title,
					'sms_content'=>$content,
					'sms_senderid'=>self::$login['uid'],
					'sms_sender'=>self::$login['nickname'],
					'sms_reciverid' =>$firstReciver['uid'],
					'sms_reciver' => $firstReciver['username']
					));
				$r = array('uid'=>0, 'username'=>'');
				$count = 0;
				$refuseList = array();
				$alist = array();
				foreach($recievers as $i=>$reciever){
					$user = member_util_login::getMemberInfoByName($recievers[0],array('uid','username'));//Cache::cacheFunction(array($this->SL, 'soap_query_user_by_username'), array($reciever));
					if($user){
						if($i==0){
							$r['uid'] = $user['uid'];
							$r['username'] = $user['username'];
						}
						// check privacy setting
						/*$allow = sms_util_verifier::checkAllow($user['acc_id'], self::$login['uid']);
						if(!$allow){
							array_push($refuseList, $user['acc_id']);
							continue;
						}*/
						
						$this->sms->addRel(
							array(
								'sms_id'=>$sms_id, 
								'sms_uid'=>$user['uid'], 
								'sms_username'=>$user['username'],
								'sms_type'=>($user['uid']==$uid?0:1),
								'sms_last_msid'=>($user['uid']==$uid?0:$sms_id),
								'sms_lastsend_msid'=>($user['uid']==$uid?$sms_id:0)
							)
						);
						if($user['uid'] != self::$login['uid'] and $allow){
							array_push($alist, $user['uid']);
						}
						CacheManager::getInstance()->refresh($this->app, '', $r['uid']);
						$count ++;
					}
				}
				
				if($count<1){
					$this->ret = self::failure(self::ERROR_NO_RECIEVER );
					$this->sms->rollback($sms_id,true);
					$this->sms->rollback($sms_id,false);
					return;
				}
				if($count>1)
					$this->sms->upSmsNums($sms_id,$count-1);
				/*$msg_id = $this->sms_message->add(
					array('sms_id'=>$sms_id, 'sender_id'=>self::$login['uid'], 'sender_name'=>self::$login['nickname'], 
						'reciever_id'=>$r['uid'], 'reciever_name'=>$r['username'],
						'title'=>$title, 'content'=>$content, 'type'=>self::TYPE_USER )
				);
				foreach($refuseList as $refuse){
					$this->sms_message->remove($msg_id, $refuse);
				}
				$this->sms_reciever->updateLastMessage($msg_id, $sms_id, $alist);
				$this->sms_reciever->updateLastSend($msg_id, $sms_id, $uid);*/
				$this->ret = array('result'=>true);
				$this->addMessage('短信发送成功');
				CacheManager::getInstance()->refresh($this->app);
			}
		}
		
		
	}
	
	public function reply_action(){
		$this->_renderJson();
		if(!self::$login){
			$this->ret = array('result'=>false, 'reason'=>Error::ERROR_NOT_LOGIN );
		}else{
			$uid = self::$login['uid'];
			if(Plugin::vcode_get($uid)){
				if(vcode_get2(Cache::getInstance(), 'vcode')!=strtoupper(_('vcode'))){
					$this->ret = self::failure(Error::ERROR_VCODE );
					return;
				}else{
					Plugin::vcode_clean();
				}
			}
//			if(vcode_get2(Cache::getInstance(), 'vcode')!=strtoupper(_('vcode'))){
//				$this->ret = self::failure(Error::ERROR_VCODE );
//				return;
//			}
			$sms_id = _('sms_id', 0);
			$uid = self::$login['uid'];
			$username = self::$login['nickname'];
			$check = true;//$this->sms_reciever->check($sms_id, $uid);
			if(!$check){
				$this->ret = self::failure(Error::ERROR_WRONG_OWNER );
			}else{
				$recievers = $this->sms->getReciverByUid($sms_id,$uid);
				/*if(!$reciever){
					$this->ret = self::failure(Error::ERROR_SELF , '您不能发短信给自己');
					return;
				}*/
				/*
				$sms_id = $this->sms->add(
					array('sms_title'=>$title,
					'sms_content'=>$content,
					'sms_senderid'=>self::$login['uid'],
					'sms_sender'=>self::$login['nickname'])
					);*/
				$msg_id = $this->sms->add(
					array(
						'sms_senderid'=>$uid, 
						'sms_sender'=>$username,
						'sms_reciverid'=>$recievers[0]['uid'] ,
						'sms_reciver'=>$recievers[0]['username'],
						'sms_content'=>sms_util_text::filter_html(_('content')), 
						'sms_pid'=>$sms_id
					)
				);
				
				if($msg_id){
//					$this->sms->updateCount($sms_id);
//					$recievers = $this->sms_reciever->getRecievers($sms_id);
//					$recievers = $this->sms->getReciverByUid($sms_id,$uid);
					$alist = array();
					$blist = array();
					foreach($recievers as $reciever){
						if(self::$login['uid'] == $reciever['uid']) continue;
						$allow = sms_util_verifier::checkAllow($reciever['uid'], self::$login['uid']);
						if($allow){
							array_push($alist, $reciever['uid']);
							$this->sms->updateSmsCount($reciever['uid'],1);//更新未读消息数
						}else{
							array_push($blist, $reciever['uid']);
						}
					}					
					$this->sms->updateLastSendSms($msg_id,$sms_id,$uid);//更新最后发送的短消息
					$this->sms->updateLastReciveSms($msg_id,$sms_id,$alist); //更新最后短消息					
					foreach($alist as $a){
						CacheManager::getInstance()->refresh($this->app, '', $a);
					}					
					/*foreach ($blist as $b){
						$this->sms_message->remove($msg_id, $b);
					}*/
					CacheManager::getInstance()->refresh($this->app);
				}
				$this->ret = self::success($msg_id);
				
				$this->addMessage('短信已回复。');
			}
		}
		
	}
	private function parsids($str,$op1='|',$op2 = ':'){
			$arrids[0] = array();
			$arrids[1] = array();
			$tmid = explode($op1,$str);
			foreach ($tmid as $v){
				list($smsid,$msgid) = explode($op2,$v);
				array_push($arrids[0],$smsid);
				array_push($arrids[1],$msgid);
			}
		return $arrids;
}
	public function refuse_action(){
		$this->_renderJson();
		if(!self::$login){
			$this->ret = self::failure(Error::ERROR_NOT_LOGIN );
		}else {
			$uid = self::$login['uid'];
			$sms_id = _('sms_id', 0);
			$msg_id = _('id', 0);
			$isAll = _('all',0);
			if($isAll==1){
				$msg_id = '';
			}
			elseif(preg_match('/[:|]+/',$msg_id)){
				$mids = $this->parsids($msg_id);
				$sms_id = $mids[0];
				$msg_id = $mids[1];
			}
			$flag = $this->sms->delReciverSms($uid,$msg_id);
			if($flag){
				$this->ret = self::success();
				if ($isAll==1) {
					$this->addMessage('清空收件箱成功！');
				}
				else{
					$this->addMessage("短消息删除成功！");
				}
				CacheManager::getInstance()->refresh($this->app);
			}else{
				$this->ret = self::failure(Error::ERROR_UNKNOWN );
			}
		}
	}
	
	public function remove_action(){
		$this->_renderJson();
		if(!self::$login){
			$this->ret = self::failure(Error::ERROR_NOT_LOGIN );
		}else{
			$uid = self::$login['uid'];
			$id = $this->id;
			$isAll = _('all',0);
			if($isAll==1){
				$id = '';
			}
			elseif(preg_match('/[:|]+/',$id)){
				$mids = $this->parsids($id);
				$sms_id = $mids[0];
				$id = $mids[1];
			}
			$flag = $this->sms->delSendSms($uid,$id);
			if($flag){
				$this->ret = self::success();
				CacheManager::getInstance()->refresh($this->app);
			}else{
				$this->ret = self::failure(Error::ERROR_UNKNOWN );
			}
		}
	}
	
	public function delete_action(){
		
	}
	
	public function view_read_action(){
//		if($this->reload) $this->additionView= $this->viewDir."/_addtion.phtml";
		$this->requireLogin();
		$uid = self::$login['uid'];
		$sms_id = _('sms_id', 0);
		//$sms = $this->sms->getReciveSmsInfo($sms_id);
		$this->view = 'read';
		$sms =CacheManager::getInstance()->get(array(
			'app'=>$this->app,
			'func'=>array(
				array($this->sms, 'getReciveSmsInfo'),
				array($sms_id)
			)
		));
		if(!$sms){
			$this->ret = self::failure(Error::ERROR_RECORD_NOT_FOUND , array('记录不存在'));
			return;
		}
		/*$recievers = CacheManager::getInstance()->get(array(
			'app'=>$this->app,
			'func'=>array(
				array($this->sms_reciever, 'select'),
				array($sms_id)
			)
		));*/
		$recievers2 = array();
		$delSmsId = array();
		$exists = false;
		foreach($sms as $i=>$reciever){
			if($reciever['sms_type']==0){
				$smsPid = $reciever['sms_id'];
			}
			if($reciever['sms_uid']==$uid) {
				$exists = true;
				if ($reciever['sms_del'] && $reciever['sms_lastdel_msid']) {//如果是自己删除的会话
					array_push($delSmsId,$reciever['sms_lastdel_msid']);
				}
			}else{
				array_push($recievers2, "<a href='/?uid=".$reciever['sms_uid']."'>".$reciever['sms_username']."</a>");
			}
		}
		if(!$exists){
			$this->ret = self::failure(Error::ERROR_WRONG_OWNER);
			return;
		}
		$messages = CacheManager::getInstance()->get(array(
			'app'=>$this->app,
			'func'=>array(
				array($this->sms, 'getSmsInfoById'), 
				array($sms_id)				
			)
		));
		$this->ret = self::success(array('sms'=>$sms,'recievers'=>$recievers2, 'messages'=>$messages,'delsmsid' =>$delSmsId,'sms_pid'=>$smsPid));
		
	}
	
	public function rollback($sms_id){
		$this->sms->rollback($sms_id);
		$this->sms->rollback($sms_id,false);
	}
	
	public function check_new_action(){
		$rtype = _('rtype', 1);
		$simple = false;
		if($rtype==1){
			$this->_renderJson();
		}elseif($rtype==2){
			$this->_renderJson2();
			$simple = true;
		}elseif($rtype==3){
			$this->_renderSingle('nav_check_new');
			$simple = true;
		}elseif($rtype==4){
			$this->_renderSingle('nav_check_new2');
			$simple = true;
		}
		$uid = $this->getUid();
		if($uid){
			header("Expires: ".gmtmkDate(time()+300));
			/*$ret = CacheManager::getInstance()->get(array(
				'app'=>'sms',
				'func'=>array(
					array($this, 'checkNew'),
					array($uid, $simple)
				)
			));*/
			$ret = $this->checkNew($uid,$simple);
/*			$ret = $this->checkNew($uid,$simple);*/
			$this->ret = self::success($ret);
		}else{
			$this->ret = self::failure(Error::ERROR_NOT_LOGIN );
		}
	}
	
	public function checkNew($uid, $simple=false){
		$ret = array();		
		$newNum = $this->sms->queryUnReadSms($uid);
		$ret['message'] = isset($newNum['smsnum'])?$newNum['smsnum']:'0';//$this->sms_reciever->getUnread($uid,1);
		$ret['system'] =  isset($newNum['sysnum'])?$newNum['sysnum']:'0';//$this->sms_reciever->getUnread($uid,0);
		if($uid && ($anno = MemRow::getCache(CACHE_KEY_SYS_ANNO)) && $anno['time']>$newNum['announcement'] ){
			$ret['announcement'] = 1;	
		}else 
			$ret['announcement'] = 0;
//		$ret['announcement'] = isset($newNum['announcement'])?$newNum['announcement']:0;//Model::factory("sms_model_annlog")->getUnread($uid,0);
		if(!$simple){
			$ret['friends'] 	= 	isset($newNum['friendsnum'])?$newNum['friendsnum']:'0';//$this->sms_reciever->getUnreadAppRequest($uid,'friends|add');
			$ret['buff'] 		= 	isset($newNum['buffnum'])?$newNum['buffnum']:'0';//$this->sms_reciever->getUnreadAppRequest($uid,'buff');	
			$ret['gift'] 		= 	isset($newNum['giftnum'])?$newNum['giftnum']:'0';//$this->sms_reciever->getUnreadAppRequest($uid,'gift');
			$ret['cite'] 		= 	isset($newNum['citenum'])?$newNum['citenum']:'0';//$this->sms_reciever->getUnreadAppRequest($uid,'gift');
			$ret['comnum'] 		= 	isset($newNum['comnum'])?$newNum['comnum']:0;
			$ret['recomment'] 	= 	isset($newNum['recomment'])?$newNum['recomment']:0;
			$ret['msgnum'] 		= 	isset($newNum['msgnum'])?$newNum['msgnum']:0;
			$ret['remsgnum'] 	= 	isset($newNum['remsgnum'])?$newNum['remsgnum']:0;
			$ret['dkpnum'] 		= 	isset($newNum['dkpnum'])?$newNum['dkpnum']:0;
			$ret['anim'] 		= 	isset($newNum['anim'])?$newNum['anim']:0;
			$ret['cartoon'] 	= 	isset($newNum['cartoon'])?$newNum['cartoon']:0;
			$ret['fiction'] 	= 	isset($newNum['fiction'])?$newNum['fiction']:0;
			$ret['subscribe']	=	$ret['dkpnum']+$ret['anim']+$ret['fiction']+$ret['cartoon'];
		}
		$ret['total'] = $ret['message']+$ret['system']+$ret['announcement']+$ret['comnum']+$ret['recomment']+$ret['msgnum']+$ret['remsgnum']+$ret['subscribe'];
		return $ret;
	}
	
	public function getNewSmsNum_action(){
		$this->_renderJson();
		$uid = self::$login['uid'];
		if(!$uid)  $this->ret = self::failure(Error::ERROR_NOT_LOGIN );
		if($ret = $this->checkNew($uid,false)){
			$this->ret = self::success($ret);
		}
		else
			$this->ret = self::failure(Error::ERROR_RECORD_NOT_FOUND );
		
	}
	
	
	public function send_interface_action(){
		$this->_renderJson();		
//		$arguments = filter_params($_REQUEST, 'title', 'content', 'reciever_id', 'sender_id', 'sender_name', 'time', 'encoding');
		trim_params($arguments);
		$checksum = $_REQUEST['checksum'];
		$checksum2 = md5(implode("|", $arguments)."|".$_SERVER['config']['sms']['syskey']);

		if($checksum!=$checksum2){
			$this->ret = self::failure(Error::ERROR_CHECKSUM );
			return;
		}		
		if(strtoupper($arguments['encoding']) != 'UTF-8'){
			trim_params($arguments, create_function('$s', 'return iconv("gb18030", "utf-8", $s);'));
		}		
		extract($arguments);		
		if(abs($_SERVER['REQUEST_TIME']-$time)>60000){
			$this->ret = self::failure(Error::ERROR_EXPIRE );
			return;
		}
		if(!$content){
			$this->ret = self::failure(Error::ERROR_DATA);
			return ;
		}
		if($sender_id!=0){
			$uid = $sender_id;
			$recievers = explode(",", $reciever_id);
			array_push($recievers, $sender_id);
//			$recievers = array_unique($recievers);
			$firstReciver = Cache::cacheFunction(array($this->SL, 'soap_query_user'), array($recievers[0]));
			$sms_id = $this->sms->add(
				array('sms_title'=>$title,
					'sms_content'=>$content,
					'sms_senderid'=>$sender_id,
					'sms_sender'=>$sender_name,
					'sms_reciverid' =>$firstReciver['acc_id'],
					'sms_reciver' => $firstReciver['acc_nickname']
					)
			);
			$r = array('uid'=>0, 'username'=>'');
			$count = 0;
			foreach($recievers as $i=>$reciever){
				try{
					$user = Cache::cacheFunction(array($this->SL, 'soap_query_user'), array($reciever));
				}catch(Exception $e){
					continue;
				}
				if($user){
					if($i==0){
						$r['uid'] = $user['acc_id'];
						$r['username'] = $user['acc_nickname'];
					}
					$newPm = $user['acc_id']==$uid?false:true;
					$this->sms->addRel(array(
								'sms_id'=>$sms_id, 
								'sms_uid'=>$user['acc_id'], 
								'sms_username'=>$user['acc_nickname'],
								'sms_type'=>($user['acc_id']==$uid?0:1),
								'sms_last_msid'=>($user['acc_id']==$uid?0:$sms_id),
								'sms_lastsend_msid'=>($user['acc_id']==$uid?$sms_id:0)
							),$newPm);
					CacheManager::getInstance()->refresh($this->app, '', $user['acc_id']);
					$count ++;
				}
			}
				
			if($count<count($recievers)){
				$this->ret = self::failure(self::ERROR_NO_RECIEVER );
				$this->sms->rollback($sms_id,true);
				$this->sms->rollback($sms_id,false);
				return;
			}			
			/*$msg_id = $this->sms_message->add(
				array('sms_id'=>$sms_id, 'sender_id'=>$sender_id, 'sender_name'=>$sender_name, 
					'reciever_id'=>$r['uid'], 'reciever_name'=>$r['username'], 'title'=>$title,
					'content'=>$content, 'type'=>self::TYPE_USER )
			);*/
//			$this->sms_reciever->updateLastMessage($msg_id, $sms_id, $sender_id, $sender_id==$reciever_id);
//			$this->sms_reciever->updateLastSend($msg_id, $sms_id, $sender_id);
			$this->ret = array('result'=>true);
		}else{
			$sys_sms = new sms_model_system;
			$type = 0;
			$recievers = explode(",", $reciever_id);
			$recievers = array_unique($recievers);
			$firstReciver = Cache::cacheFunction(array($this->SL, 'soap_query_user'), array($recievers[0]));
			$username = $sender_name = $sender_name?'[:'.$sender_name.':]':'[:system:]';
			$sms_id = $sys_sms->add(array(
				'senderid' => 0,
				'sender' => $username,
				'recieverid' => $firstReciver['acc_id'],
				'reciever' => $firstReciver['acc_nickname'],
				'content' => $content,
				'target' =>serialize(array('id'=>0))
			)
			);			
			if(!$sms_id){
				$this->ret = self::failure(Error::ERROR_UNKNOWN );
				return; // 数据库错误
			}
			
			foreach($recievers as $i=>$reciever){
				try{
					$user = Cache::cacheFunction(array($this->SL, 'soap_query_user'), array($reciever));
				}catch(Exception $e){
					continue;
				}
				if($user){
					if($i==0){
						$r['uid'] = $user['acc_id'];
						$r['username'] = $user['acc_nickname'];
					}
					$flag = $sys_sms->addRel(array(
						'sms_id'=>$sms_id,
						'reciever_id'=>$user['acc_id'],
						'reciever'=>$user['acc_nickname'],
						'readed'=>($user['acc_id']==$uid?0:1)
						)
					);
					if($flag) $count ++;
				}
			}
			
			if($count<count($recievers)){
				$this->ret = self::failure(self::ERROR_NO_RECIEVER );
				$sys_sms->rollback($sms_id,true);
				return; // 收件人填写错误
			}/*			
			$flag = $this->sms_message->add(
				array('sms_id'=>$sms_id, 'sender_id'=>0, 'sender_name'=>$username,
				'reciever_id'=>$r['uid'], 'reciever_name'=>$r['username'], 'title'=>$title,
				'content'=>$content, 'type'=>$type )
			);
			
			if(!$flag){
				$this->ret = self::failure(Error::ERROR_UNKNOWN ); // 数据库错误
				$this->rollback($sms_id);
			}*/else{
				$this->ret = array('result'=>true);
			}
			
			foreach($recievers as $uid){
				CacheManager::getInstance()->refresh($this->app, '',$uid);
			}
		}
	}
}
